<?php
/***************************************************************************
 * 
 * Copyright (c) 2010 , Inc. All Rights Reserved
 * 
 **************************************************************************/
 
 
 
/**
 * @file Encoding.php
 * @author huqingping
 * @date 2010/09/01 15:08:45
 * @brief 
 *  
 **/

final class Encoding
{
    static function convert($value,$to,$from)
    {
        if ($value == null) {
            return $value;
        }
        //有ccode库
        $isccode = function_exists('is_gbk');
        //专门有处理gbk/utf8转码的扩展，解决一些badcase
        if ($to === 'GBK' && ($from === 'UTF-8' || $from === 'UTF8') && $isccode) {
            $v = utf8_to_gbk($value,strlen($value),UCONV_INVCHAR_REPLACE);
            if ($v !== false) {
                return $v;
            } else {
                Logger::warning("utf8_to_gbk fail str=%s",bin2hex($value));
            }
        }
        if (($to === 'UTF-8' || $to === 'UTF8') && $from === 'GBK' && $isccode) {
            $v = gbk_to_utf8($value,strlen($value),UCONV_INVCHAR_REPLACE);
            if ($v !== false) {
                return $v;
            } else {
                Logger::warning("gbk_to_utf8 fail str=%s",bin2hex($value));
            }
        }
        //return mb_convert_encoding($value,$to,$from); 
        //mb_convert会由于字符编码问题出fatal，改成iconv //ignore模式
        return iconv($from,$to.'//ignore',$value); 
    }

	static function convertArray(&$arr,$to,$ie)
	{
		foreach($arr as $key=>&$value) {
			if (is_array($value)) {
                self::convertArray($value,$to,$ie);
			} elseif(is_string($value)) {
				$value = self::convert($value,$to,$ie);
			}
		}
	}
}






/* vim: set expandtab ts=4 sw=4 sts=4 tw=100: */
